package cn.cityre.tools.crestat;

import cn.cityre.tools.db.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


/**
 * @author sunzhaoye
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = { "cn.cityre.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {

	@Autowired
	Environment env;

	@Bean
	public PlatformTransactionManager dynamicTransactionManager(
			@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource) {
		return new DataSourceTransactionManager(dynamicDataSource);
	}

	@Bean
	public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource);
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactory.setMapperLocations(resolver.getResources("classpath:mybatis/citydb/*.xml"));
		sqlSessionFactory.setConfigLocation(resolver.getResource("classpath:mybatis/config/MainConfig.xml"));
		return sqlSessionFactory.getObject();
	}

}
